'use strict'
// ipcMain（主进程中使用的对象）
import { app, protocol, BrowserWindow, ipcMain, screen , dialog, shell} from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import { download } from 'electron-dl' // 加载 electron-dl 模块
import fs from 'fs'
import path from 'path'
// import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'

// 用于跟踪当前下载项
let downloadItem = null;

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 720,
    height: 420,
    frame: false,
    resizable:false,
    webPreferences: { 
      // 使渲染进程拥有node环境 
      // nodeIntegration: true,  
      //关闭web权限检查，允许跨域 
      webSecurity: false, 
      webviewTag: true,
      enableBlinkFeatures: 'Geolocation',
      contextIsolation: false,
      devTools: true,
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION, 
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION 
    }
  }) 
  win.setMenu(null);
  // 监听最大化后重新执行最大化逻辑，修复最大化后四周黑边和顶部白边的问题
  win.on('maximize', (e) => {
    e.preventDefault() 
    const { width, height } = screen.getPrimaryDisplay().workAreaSize
    win.setMaximumSize(width, height)
    win.getMaximumSize()
    win.setSize(width, height)
    win.center() 
  });
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html') 
  }
  // 改变窗口大小监听
  ipcMain.on('changeWindowSize', (event, arg) => {
    
    win.resizable = true;
    // mainWindow为主进程new的BrowserWindow实例
    if(arg.path=='home'){
      win.setMinimumSize(1000, 640)
      win.setSize(arg.width, arg.height)
      win.resizable = true;
    }else{
      if (win.isMaximized()) { 
        win.restore();
      }
      win.setMinimumSize(720, 420)
      win.setSize(arg.width, arg.height)
      win.resizable = false;
    }
    // console.log(arg.width, arg.height)
    win.center()
    event.returnValue = "changeWindowSize"
  })
  // 顶部菜单全屏、最小化、关闭监听
  ipcMain.on('operateMenu', (event, arg) => {
    win.resizable = true;
    if(arg=='min') win.minimize(); 
    else if(arg=='max') win.maximize();
    else if(arg=='resize') win.restore();
    else if(arg=='close'){
      win.hide(); 
      win.close();
    }
    event.returnValue = "operateMenu"
  })
  // 监听渲染进程发送的事件，选择软件
  ipcMain.on('open-file-dialog', (event) => {
    dialog.showOpenDialog(win, {
      properties: ['openFile'],
    }).then(result => {
      if (!result.canceled && result.filePaths.length > 0) {
        const filePath = result.filePaths[0];
      // 获取文件图标
      app.getFileIcon(filePath).then(icon => {
        // 发送文件路径和图标给渲染进程
        event.sender.send('selected-file', {
          path: filePath,
          icon: icon.toDataURL() // 将图标转换为DataURL
        });
      }).catch(err => {
        console.error('Error fetching file icon:', err);
      });
      }
    }).catch(err => {
      console.error(err); 
    }); 
    event.returnValue = "choseSoft"
  });
  // 打开下载目录
  ipcMain.on('open-folder', (event) => {
    const folderPath = 'D:\\CodeRealm\\app';
    
    // 检查文件夹是否存在，不存在则创建
    if (!fs.existsSync(folderPath)) {
      fs.mkdirSync(folderPath, { recursive: true });
    }
    
    // 打开文件夹
    shell.openPath(folderPath).then(() => {
      event.sender.send('folder-opened', true);
    }).catch(err => {
      console.error('打开文件夹失败:', err);
      event.sender.send('folder-opened', false);
    });
  });
  // 文件下载监听
  ipcMain.on('download-file', (event, { url, savePath }) => {
    console.log(url, savePath)
    const win = BrowserWindow.getFocusedWindow();
    // 移除之前的 will-download 监听器
    win.webContents.session.removeAllListeners('will-download');
    win.webContents.session.on('will-download', (eve, item) => {
      downloadItem = item;
      item.setSavePath(path.join(savePath, item.getFilename()));
      
      item.on('updated', () => {
        win.webContents.send('download-progress', {
          percent: item.getReceivedBytes() / item.getTotalBytes()
        });
      });

      item.on('done', (e, state) => {
        console.log(state)
        if (state === 'completed') {
          event.sender.send('download-success', item.getSavePath());
        } else if(state === 'cancelled'){
          event.sender.send('download-error', '下载已取消');
        } else {
          event.sender.send('download-error', '下载失败');
        }
        downloadItem = null;
      });
    });

    win.webContents.downloadURL(url);
  });
  
  ipcMain.on('cancel-download', () => {
    if (downloadItem) {
      downloadItem.cancel();
      downloadItem = null; // 清除下载项引用
    }
  });
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // let extensionPath = "C:\\Users\\fjk\\AppData\\Local\\vue-dev\\5.1.1_0";
    // BrowserWindow.addDevToolsExtension(extensionPath)
    // Install Vue Devtools
    // try {
    //   await installExtension(VUEJS3_DEVTOOLS)
    // } catch (e) {
    //   console.error('Vue Devtools failed to install:', e.toString())
    // }
  }
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
